<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Pg extends CI_Controller {
	var $perpage = 20;

		public function __construct() {
		   parent::__construct();
		   if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) redirect('auth/login/'.str_replace("/", ".",$_SERVER['REQUEST_URI']));
		   $this->layout->setlayout('admin/layout');
		   $this->crumps->push('/admin/pg/', 'Фотогалереи');
		   $this->users_rights_model->check_rights(strtolower(get_class()), $this->router->get_method());
	   }

	public function index()	{

		$data['from'] = $from = $this->input->get('from', true);
		if ($from == "") $from = 0;
		$data['pages'] = $pages = $this->db->select()->from('pg')->limit($this->perpage, $from)->get()->result_array();

		/* pagination */
		$count = $this->db->select()->from('pg')->count_all_results();
		if ($from != 0 && sizeof($pages) <= 0 && $count > 0) {
			$pgng = $from - $this->perpage;
			redirect('admin/pg/index/?from='.$pgng);
		}
		$this->load->library('pagination');
		$config['base_url'] = '/admin/pg/index/';
		$config['total_rows'] = $count;
		$config['page_query_string'] = TRUE;
		$config['per_page'] = $this->perpage;
		$this->pagination->initialize($config);
		$data['paging'] = $this->pagination->create_links();
		/* pagination */

		$this->layout->view('admin/pg/index', $data);
	}
	public function edit($id = 0, $ajax = false) {
		$this->crumps->push('/admin/pg/'.($id == 0?'add':'edit/'.$id).'/', ($id == 0?"Добавление":"Редактирование"));
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('pg')->where('pg_id', $id)->get()->row_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/pg');

		$form = new jQuickForm('pg_simple');

		$random = md5(time()).md5(md5(time()));
		$random2 = md5(time()).md5(time());

		$form->addElement('hidden', 'random')->setValue($random);
		$form->addElement('hidden', 'random2')->setValue($random2);
		$form->setLabel(($id == 0?"Добавление":"Редактирование").' фотогалереи');

		$form->insertInputText('pg_title')->setLabel('Название')->addRuleRequired();
		if ($ajax == false) {
			$gr = $form->insertGroup()->addClass('col col2');
			$date = $gr->insertInputText('pg_video')->setLabel('Ссылка на видео')->setExample('http://www.youtube.com/watch?v=doESOP2gLVQ');

			$select = $gr->insertSelect('pg_parent')->setLabel('Раздел для галереи');
			$parents[1] = 'Фотогалереи';
			$parents[2] = 'Для новостей';
			$parents[3] = 'Видеозаписи';
			foreach ($parents as $key => $val) {
				$select->addOption($val, $key);
			}
			if($page['pg_parent'] == 3)$form->insertInputCheckbox('pg_main', '1')->setLabel('Отображать в правой колонке');
		} else {
			$form->addElement('hidden', 'pg_parent')->setValue('2');
		}

			/* ГЛАВНАЯ ФОТКА */
			if ($id != 0 && $page['pg_image'] != "") {
				$file = $page['pg_image'];
				$im = getimagesize('./uploads/pg/'.$id.'/small/'.$file);
				$padding = round((150 - $im[1]) / 2);
				$text = "<div class=\"multi_upload_preview\"><img style='margin: ".$padding."px 0 0 0;' src='/uploads/pg/".$id."/small/".$file."' alt='Новое изображение' title='Новое изображение' /><a href='#' rel=\"one:uploads:pg:".$id.":".$file."\" class='deleteimage'><img src='/data/images/icons/delete.png' alt='Удалить' title='Удалить' /></a></div>";
			}
			$form->insertStatic("<div class='loaded_images' id='loaded_images_pg_image_0'>".$text."<br class='cc' /></div>");

			$post_params = array(
				'width' => '200',
				'height' => '200',
				'random' => $random,
				'session' => $this->session->userdata('session_id')
			);
			$form->insertMultiUpload('pg_image', '/admin/tools/upload/pg/', $post_params, 1, false, 2048000)->setId('pg_image_0')->setLabel('Главная фотография')->setComment('Максимум только одна фотография (jpg/png/gif, 1024Kb, 1000*1000px)');

			/* ГЛАВНАЯ ФОТКА */

		/* МУЛЬТИФОТОС */
		$text = "";
		if ($id != 0) {
			$mfiles = $this->db->select()->from('ph')->order_by('ph_id', 'desc')->where('ph_pg', $id)->get()->result_array();
			foreach ($mfiles as $mfile) {
				$file = $mfile['ph_file'];
				$im = getimagesize('./uploads/ph/'.$id.'/small/'.$file);
				$padding = round((150 - $im[1]) / 2);
				$text .= "<div class=\"multi_upload_preview\"><img style='margin: ".$padding."px 0 0 0;' src='/uploads/ph/".$id."/small/".$file."' alt='Новое изображение' title='Новое изображение' /><a href='#' rel=\"multi:uploads:ph:".$id.":".$file."\" class='deleteimage'><img src='/data/images/icons/delete.png' alt='Удалить' title='Удалить' /></a></div>";
			}
		}

		$form->insertStatic("<div class='loaded_images' id='loaded_images_pg_image_1'>".$text."<br class='cc' /></div>");

		$post_params = array(
			'width' => '200',
			'height' => '200',
			'random' => $random2,
			'session' => $this->session->userdata('session_id')
		);
		$form->insertMultiUpload('pg_image', '/admin/tools/upload/pg/', $post_params, 50, true, 2048000)->setId('pg_image_1')->setLabel('Фотографии для фотогалереи')->setComment('До 50 фотографий (jpg/png/gif, 1024Kb, 1000*1000px каждая)');
		/* МУЛЬТИФОТОС */

		if (($ajax == true && $_SERVER['REQUEST_METHOD'] == "POST") || ($_SERVER['REQUEST_METHOD'] == "POST" && $form->validate())) {
			if ($id == 0) {
				$p_data = $this->input->post();

				if(!$p_data['pg_main'])$p_data['pg_main'] = 0;
				$p_data['pg_date'] = time();
				$p_data['pg_status'] = 1;

				$rand = $p_data['random'];
				unset($p_data['random']);
				$rand2 = $p_data['random2'];
				unset($p_data['random2']);

				$this->db->insert('pg', $p_data);
				$result = $this->db->insert_id();

				$files = $this->tools_model->copyfiles($rand, $result, 'pg');
				if (sizeof($files) > 0) $this->db->update('pg', array('pg_image' => $files[0]), array('pg_id' => $result));

				$mfiles = $this->tools_model->copyfiles($rand2, $result, 'ph');
				if (sizeof($mfiles) > 0) {
					foreach ($mfiles as $mfile) {
						$mf_data['ph_id'] = 0;
						$mf_data['ph_file'] = $mfile;
						$mf_data['ph_date'] = time();
						$mf_data['ph_pg'] = $result;
						$this->db->insert('ph', $mf_data);
					}
				}
				if ($ajax == true) {
					echo json_encode(array('id' => $result, 'title' => $p_data['pg_title']));
					exit();
				} else {
					$this->session->set_flashdata('msg', 'Успешно добавлено');
					redirect('admin/pg/edit/'.$result.'/');
				}
			} else {
				$p_data = $this->input->post();

				if(!$p_data['pg_main'])$p_data['pg_main'] = 0;
				$rand = $p_data['random'];
				unset($p_data['random']);
				$rand2 = $p_data['random2'];
				unset($p_data['random2']);

				$files = $this->tools_model->copyfiles($rand, $id, 'pg');
				if (sizeof($files) > 0) $p_data['pg_image'] = $files[0]; else unset($p_data['pg_image']);
				$this->db->where('pg_id', $id)->update('pg', $p_data);

				$mfiles = $this->tools_model->copyfiles($rand2, $id, 'ph');
				if (sizeof($mfiles) > 0) {
					foreach ($mfiles as $mfile) {
						$mf_data['ph_id'] = 0;
						$mf_data['ph_file'] = $mfile;
						$mf_data['ph_date'] = time();
						$mf_data['ph_pg'] = $id;
						$this->db->insert('ph', $mf_data);
					}
				}

				$this->session->set_flashdata('msg', 'Успешно обновлено');
				redirect('admin/pg/edit/'.$id.'/');
			}
		}

		if ($ajax == true) {
			$form->insertStatic('<a id="send_pg" href="#" class="add_action">Добавить</a>');
		} else {
			$form->insertInputSubmit(($id == 0?"Добавить":"Сохранить"));
		}

		$form->addDataSource(new HTML_QuickForm2_DataSource_Array($page));
		$data['form'] = $form."";
		$data['js'] = jQuickForm::js()->getJsAll();
		$data['id'] = $id;
		if ($ajax == true) {
			$this->load->view('admin/pg/ajax', $data);
		} else {
			$this->layout->view('admin/pg/edit', $data);
		}
	}
	public function delete($id = 0) {
		$from = $this->input->get('from', true);
		if ($from != "" && is_numeric($from)) $pgng = "?from=".$from;
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('pg')->where('pg_id', $id)->get()->result_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/pg');
		$this->db->where('pg_id', $id)->delete('pg');
		$files = $this->db->select()->from('ph')->where('ph_pg', $id)->get()->result_array();
		foreach ($files as $file) {
			$path = "./uploads/ph/".$id."/".$file['ph_file'];
			$small = "./uploads/ph/".$id."/small/".$file['ph_file'];
			$middle = "./uploads/ph/".$id."/middle/".$file['ph_file'];
			unlink($path);
			unlink($small);
			unlink($middle);
		}
		rmdir('./uploads/ph/'.$id.'/small');
		rmdir('./uploads/ph/'.$id.'/middle');
		rmdir('./uploads/ph/'.$id);
		$this->db->where('ph_pg', $id)->delete('ph');
		$this->db->where('news_pg', $id)->update('news', array('news_pg' => 0));
		$this->session->set_flashdata('msg', 'Успешно удалено');
		redirect('admin/pg/'.$pgng);
	}
	public function block($id = 0) {
		$from = $this->input->get('from', true);
		if ($from != "" && is_numeric($from)) $pgng = "?from=".$from;
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('pg')->where('pg_id', $id)->get()->result_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/pg');
		$this->db->where('pg_id', $id)->update('pg', array('pg_status' => 0));
		$this->session->set_flashdata('msg', 'Успешно');
		redirect('admin/pg/'.$pgng);
	}
	public function unblock($id = 0) {
		$from = $this->input->get('from', true);
		if ($from != "" && is_numeric($from)) $pgng = "?from=".$from;
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('pg')->where('pg_id', $id)->get()->result_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/pg');
		$this->db->where('pg_id', $id)->update('pg', array('pg_status' => 1));
		$this->session->set_flashdata('msg', 'Успешно');
		redirect('admin/pg/'.$pgng);
	}
	public function add() {
		return $this->edit(0);
	}
	public function ajax() {
		return $this->edit(0, true);
	}
}